package com.hdax.dm.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hdax.dm.common.utils.CommonResponse;
import com.hdax.dm.common.utils.ResponseUtil;
import com.hdax.dm.constants.ResultEnumCode;
import com.hdax.dm.dtos.user.UserDto;
import com.hdax.dm.exceptions.TokenException;
import com.hdax.dm.mapstructs.UserDtoMapper;
import com.hdax.dm.service.UserService;
import com.hdax.dm.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(path = "/user")
public class RefreshTokenController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDtoMapper dtoMapper;

    @PostMapping(path = "refreshToken")
    public CommonResponse<UserDto> refreshToken(@RequestBody Map<String,String> params){
        //1. 验证请求token是否过期
        String token = params.get("token");
        Map<String, String> map = null;
        try{
            map = TokenUtil.parseToken(token);
        }catch (Exception e){

        }
        //2. 如果请求token过期则验证缓存token是否过期
        Long userId = Long.parseLong(params.get("userId"));
        Map entries = redisTemplate.opsForHash().entries("token:" + userId);
        if(entries !=null && entries.size() > 0){
            //验证token是否相同
            if(entries.get("token").equals(token)){
                //重置token(返回给客户端的token和redis存储的token)
                //重新生成token
                UserDto dto = dtoMapper.toTarget(userService.getById(userId));
                String newToken = TokenUtil.createToken(BeanUtil.beanToMap(dto,new HashMap<>(),false,true));
                //添加token信息到Redis缓存中
                //缓存数据的过期时间为token有效期的2倍
                Map<String, String> redisData = new HashMap<>();
                redisData.put("userId",dto.getUserId().toString());
                redisData.put("phone",dto.getPhone());
//                redisData.put("nickName",dto.getNickName());
                redisData.put("realName",dto.getRealName());
                redisData.put("token",newToken);
                redisTemplate.opsForHash().putAll("token:"+dto.getUserId(),redisData);
                redisTemplate.expire("token:"+dto.getUserId(),TokenUtil.TOKEN_EXPIRE_TIME * 2, TimeUnit.MILLISECONDS);
                dto.setToken(newToken);
                System.out.println(token);
                System.out.println(newToken);
                return ResponseUtil.returnSuccess(dto);
            }else{
                throw new TokenException(ResultEnumCode.TOKEN_INVALID);
            }
        }
        //3. 如果均过期则，直接返回用户重新登录
        throw new TokenException(ResultEnumCode.NEED_RELOGIN);
    }
}
